<template>
  <div class="app-container templateWrapp">
    <el-row :gutter="20">
      <el-col :span="16">
        <div class="grid-content" v-if="content.length > 0">
          <div class="leftContent" v-for="(i, index) in content" :key="index">
            <div class="close" @click="clearItem(i)"><i class="el-icon-circle-close"></i></div>
            <div class="tempDiv">
              <editor v-model="content[index].content" :min-height="192" width="794px" />
              <!-- <editors /> -->
            </div>
          </div>
          <div class="savaInfo"> <el-button type="primary" @click="saveMaterial">保存</el-button>
            <el-button type="primary" @click="saveTemplate">保存并导出为word</el-button>
          </div>
        </div>
        <div v-else style="color: #606266;text-align: center;">
          请选择右边的素材库！！！
        </div>
        <!-- 添加或修改公告对话框 -->
        <el-row>
          <el-col :span="24">
            <el-dialog :title="title" :visible.sync="open" width="66.7%" modal-append-to-body="false">
              <el-form ref="form" label-width="80px">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="内容">
                      <editor v-model="form.noticeContent" :min-height="192" width="794px" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
              </div>
            </el-dialog>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="8">
        <div class="grid-content">
          <div class="top">
            <div class="left"><img src="@/assets/images/icon/leftIcon.png" alt="" srcset=""
                style="width: 15px;height: 14px;">子素材库</div>
          </div>
          <div class="list">
            <div class="item" v-for="(i, index) in dTotal" :key="index">
              <div class="title">{{ i.name }}</div>
              <div class="content" v-for="(sub, index1) in i.children" :key="index1">
                <div class="row">
                  <div class="left">{{ sub.name }}</div>
                  <div class="right">
                    <!-- <el-autocomplete class="inline-input" v-model="i.children[index1].remark" style="width: 90%;"
                      :fetch-suggestions="querySearch" placeholder="请输入内容" @select="handleSelect" value-key="name"
                      @focus="changeInput(sub, i.children[index1].selectedMaterialName)"></el-autocomplete> -->
                    <el-popover placement="bottom" width="250" trigger="focus">
                      <div class="searchList" v-if="searchInfoList.length > 0">
                        <p class="showItem" v-for="selectInfo in searchInfoList" @click="handleSelect(selectInfo)">
                          {{ selectInfo.name }}
                        </p>
                        <el-pagination small layout="prev, pager, next" v-show="total > 0" :total="total"
                          :page.sync="queryParams.params.pageNum" :limit.sync="queryParams.params.pageSize"
                          @pagination="getMaterial" :pager-count="5">
                        </el-pagination>
                      </div>
                      <div v-else class="showLoadingTitle">
                        {{ showLoadingTitle ? '搜索中，请稍等' : '暂无数据' }}
                      </div>
                      <el-input placeholder="请输入内容" slot="reference" v-model="i.children[index1].remark"
                        @focus="changeItem(sub, i.children[index1].remark)"
                        @input="changeItem(sub, i.children[index1].remark)"></el-input>
                    </el-popover>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="savaInfo"> <el-button type="primary" @click="saveMaterial">保存</el-button>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
// import { list, forceLogout } from "@/api/monitor/online";
import { getTemplates, saveMaterial, saveWord, materialSearch } from "@/api/template/template";
import editors from '@/components/Wangeditor/editor.vue'
import { Message } from 'element-ui'
import debounce from '@/utils/debounce'
const debounceGetSearch = debounce(materialSearch, 500)
export default {
  components: {
    editors
  },
  name: "Online",
  data() {
    return {
      showLoadingTitle: true,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        "name": "",
        "params": {
          "pageSize": 10,
          "pageNum": 1
        },
        "parentId": ""
      },
      searchInfoList: [],
      visible: true,
      templateName: '',
      materialId: '',
      dTotal: [],//素材库列表
      // 表单参数
      form: {
        noticeContent: '<span>html标签在渲染的时候被源码输出1212</span>'
      },
      // 弹出层标题
      title: "详情",
      open: false,
      // content: [{
      //   content: "<span>html标签在渲染的时候被源码输出</span>",
      //   selectedMaterialId:''
      // }],
      state1: '',
      resorceArr: [],
      restaurants: [
      ],
      templateId: '',//查询的模板id
      ids: [],//保存修改的内容
      focusMaterialId: '',//焦点的id
      content: [],
    };
  },
  created() {
    // this.getList()
    let id = this.$route.query.templateId
    this.templateName = this.$route.query.templateName
    this.templateId = id;
    // console.log(id, 'templateId')
    this.getDetails()
  },
  methods: {
    async getMaterial() {
      // let res = await materialSearch(this.queryParams)
      // this.searchInfoList = res.rows
      // this.total = res.total
      debounceGetSearch(this.queryParams).then(res => {
        this.searchInfoList = res.rows
        this.total = res.total
        this.showLoadingTitle = false
        console.log(this.total, 'this.total')
      })
      // console.log(res, 888)
    },
    changeItem(sub, name) {
      this.showLoadingTitle = true
      this.searchInfoList = []
      this.queryParams.name = name;
      this.queryParams.parentId = sub.materialId;
      this.focusMaterialId = sub.materialId//焦点的id
      this.getMaterial()
    },
    async saveTemplate() {
      this.saveMaterial()
      let str = ''
      this.content.map((item) => {
        str += item.content
      })
      let res = await saveWord({ template: str })
      // console.log(decodeURI(res.headers["content-disposition"].split("filename=")[1]), 'filename')  //下载后文
      let blob = new Blob([res.data], {
        type: `application/msword` //word文档为msword,pdf文档为pdf
      });
      let objectUrl = URL.createObjectURL(blob);
      let link = document.createElement("a");
      // let fname = this.templateName; //下载文件的名字
      let fname = decodeURI(res.headers["content-disposition"].split("filename=")[1]); //下载文件的名字
      link.href = objectUrl;
      link.setAttribute("download", fname);
      document.body.appendChild(link);
      link.click();
      console.log(blob, 'res')
      // Message({ message: '导出成功', type: 'success' })
    },
    async saveMaterial() {
      let info = this.content.map(item => {
        return {
          content: item.content,
          threeLevelMaterialId: item.selectedMaterialId
        }
      })
      console.log(info)
      let data = {
        list: info,
        templateId: this.templateId,
      }
      console.log(data, '入参')
      let res = await saveMaterial(data)
      Message({ message: '保存成功', type: 'success' })
      console.log(res)
    },
    clearItem(e) {
      // console.log(e.materialId)
      for (let i = 0; i < this.ids.length; i++) { //删除id
        console.log(this.ids.indexOf(e.selectedMaterialId))
        if (this.ids.indexOf(e.selectedMaterialId) > -1) {
          // 判断 id 为 4 的对象是否存在，
          this.ids.splice(i, 1) // 存在即删除
        }
      }
      for (let i = 0; i < this.content.length; i++) { //删除内容
        console.log(this.content[i].selectedMaterialId.indexOf(e.selectedMaterialId))
        if (this.content[i].selectedMaterialId.indexOf(e.selectedMaterialId) > -1) {
          // 判断 id 为 4 的对象是否存在，
          this.content.splice(i, 1) // 存在即删除
        }
      }
      //此时还要清除树上对应的内容
      for (let k in this.dTotal) {
        for (let m in this.dTotal[k].children) {
          if (this.dTotal[k].children[m].selectedMaterialId == e.selectedMaterialId) {//选中的时候复制给需要的id
            this.dTotal[k].children[m].selectedMaterialId = ''
            this.dTotal[k].children[m].selectedMaterialName = ''
          }
        }
      }
      // console.log(this.ids, this.content)
    },
    async getDetails() {
      //每次都清空
      this.content = []
      this.ids = []
      let response = await getTemplates({ templateId: this.templateId })
      this.dTotal = response.data.materialTree;
      this.content = response.data.materialToTemplateDto.list.map(item => {
        return {
          selectedMaterialId: item.threeLevelMaterialId,
          content: item.content
        }
      })
      this.ids = response.data.materialToTemplateDto.list.map(item => {
        return item.threeLevelMaterialId
      })
      console.log(this.content, 'this.content', this.ids)
    },
    handleSelect(item) {
      // console.log(item);
      let isSelect = this.ids.includes(item.materialId)
      if (!isSelect) {//没有选中 的时候就添加进去
        this.ids.push(item.materialId)
        this.content.push({
          content: item.content,
          selectedMaterialId: item.materialId
        })
      } else {
        Message({ message: '您已添加该素材', type: 'error' })
      }
      for (let k in this.dTotal) {
        for (let m in this.dTotal[k].children) {
          if (this.dTotal[k].children[m].materialId == this.focusMaterialId) {//选中的时候复制给需要的id
            this.dTotal[k].children[m].selectedMaterialId = item.materialId
            this.dTotal[k].children[m].remark = null//单纯的将弹框关闭
          }
        }
      }
    },
    filterChildren() {
      for (let k in this.dTotal) {
        for (let m in this.dTotal[k].children) {
          if (this.dTotal[k].children[m].materialId == this.focusMaterialId) {
            this.resorceArr = this.dTotal[k].children[m].children
          }
        }
      }
      // console.log(this.resorceArr, 'this.resorceArr')
    },
    changeInput(e, value) {
      // console.log(value)
      this.focusMaterialId = e.materialId//焦点的id
      this.filterChildren()
      // console.log(111, e)
    },
    getList() {
      list().then(response => {
        this.dTotal = response.rows;
        console.log(this.dTotal, 'dTotal')
      });
    },
    /** 提交按钮 */
    submitForm: function () {

    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    showDialog() {
      this.open = true
    },
    querySearch(queryString, cb) {
      // console.log(222)
      var restaurants = this.resorceArr;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },

  }
};
</script>
<style scoped lang="scss">
::v-deep .el-dialog__wrapper {
  // margin-left: -122px !important;
  // top: 0;
  // right: auto !important;
  // bottom: auto !important;
  left: -6% !important;
  // overflow: auto !important;
  // margin: 0 !important;
}

// ::v-deep .searchList:hover>showItem {
//   background: #f8f7f7 !important;
//   cursor: pointer !important;
// }

.searchList p:hover {
  background: #f8f7f7 !important;
  cursor: pointer !important;
}

.savaInfo {
  margin-top: 20px;
}

.showLoadingTitle {
  color: #333;
  text-align: center;
  font-size: 14px;
}

.leftContent {
  cursor: pointer;
  position: relative;
  padding: 0 20px 20px 20px;
  border: 1px solid #828282;
  border-radius: 6px;
  margin-bottom: 15px;

  .close {
    position: absolute;
    top: 10px;
    cursor: pointer;
    right: 10px;
  }

  .tempDiv {
    margin-top: 30px;
  }
}


.list {
  display: flex;
  flex-direction: column;

  .item {
    margin-top: 10px;

    .title {
      color: #F9B37D;
      font-family: PingFang SC;
      font-size: 14px;
      font-style: normal;
      font-weight: 500;
      line-height: normal;
      text-align: left;
    }

    .content {
      margin-top: 15px;
      color: #333;
      font-family: PingFang SC;
      font-size: 14px;

      .row {
        margin-top: 15px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .left {
          width: 35%;
        }

        .right {
          width: 65%;
          display: flex;
          align-items: center;

          .searchList {
            p {
              &:hover {
                background: #f8f7f7;
                cursor: pointer;
              }
            }
          }

          .close {
            font-size: 22px;
            margin-left: 10px;
            cursor: pointer;
          }
        }
      }
    }
  }
}

.top {
  display: flex;
  justify-content: space-between;
  color: #333;
  margin: 0 0 15px 0;

  .left {
    img {
      margin-right: 10px;
    }
  }

  .right {}
}
</style>
